package com.lijian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lijian.common.domain.R;
import com.lijian.common.exception.BadRequestException;
import com.lijian.common.exception.ForbiddenException;
import com.lijian.user.config.JwtProperties;
import com.lijian.user.domain.dto.LoginFormByEmailDTO;
import com.lijian.user.domain.dto.LoginFormDTO;
import com.lijian.user.domain.po.User;
import com.lijian.user.domain.vo.UserLoginVO;
import com.lijian.user.enums.UserStatus;
import com.lijian.user.mapper.UserMapper;
import com.lijian.user.service.IUserService;
import com.lijian.user.util.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author LiJian
 * @date 2024-10-22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private final JwtTool jwtTool;

    private final JwtProperties jwtProperties;

    private final UserMapper userMapper;

    private final StringRedisTemplate stringRedisTemplate;

    @Value("${minio.url}")
    private String url;
    @Override
    public UserLoginVO login(LoginFormDTO loginDTO) {
        //1.数据校验
        String phone = loginDTO.getPhone();
        //2.根据用户名或手机号查询
        String captcha = loginDTO.getCaptcha();
        String hashKey = "login:sms:captcha:" + phone;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        User user = userMapper.selectOne(queryWrapper);
        //4.验证码校验
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(hashKey);
        if (user!=null&&hashOps!=null){
            // 3.校验是否禁用
            if (user.getStatus() == UserStatus.FROZEN) {
                throw new ForbiddenException("用户被冻结");
            }
            String captchaRedis = hashOps.get("captcha");
            if (captchaRedis==null){
                throw new BadRequestException("验证码错误");
            }else {
                if (captchaRedis.equals(captcha)){
                    // 5.生成TOKEN
                    String token = jwtTool.createToken(user.getId(), jwtProperties.getTokenTTL());
                    // 6.封装VO返回
                    UserLoginVO vo = new UserLoginVO();
                    vo.setUserId(user.getId());
                    vo.setUsername(user.getUsername());
                    vo.setToken(token);
                    return vo;
                }else {
                    throw new BadRequestException("验证码错误");
                }
            }
        }else {
            if (hashOps==null){
                throw new BadRequestException("验证码错误");
            }
            String captchaRedis = hashOps.get("captcha");
            if (captchaRedis.equals(captcha)){
                //注册新用户
                User user1 = new User();
                user1.setUsername("用户"+phone);
                user1.setStatus(UserStatus.NORMAL);
                user1.setPhone(phone);
                user1.setAvatar(url+"/system/avatar.jpg");
                user1.setPassword("123465");
                userMapper.insert(user1);
                //查询新用户id
                QueryWrapper<User> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("phone", phone);
                User user2 = userMapper.selectOne(queryWrapper2);
                // 5.生成TOKEN
                String token = jwtTool.createToken(user2.getId(), jwtProperties.getTokenTTL());
                // 6.封装VO返回
                UserLoginVO vo = new UserLoginVO();
                vo.setUserId(user2.getId());
                vo.setUsername(user2.getUsername());
                vo.setToken(token);
                return vo;
            }else {
                throw new BadRequestException("验证码错误");
            }
        }


    }

    @Override
    public UserLoginVO loginByEmail(LoginFormByEmailDTO loginFormByEmailDTO) {
        // 1.数据校验
        String email = loginFormByEmailDTO.getEmail();
        String password = loginFormByEmailDTO.getPassword();
        // 2.根据用户名或手机号查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        User userDB = userMapper.selectOne(queryWrapper);
        if (userDB!=null&&userDB.getPassword().equals(password)){
            // 5.生成TOKEN
            String token = jwtTool.createToken(userDB.getId(), jwtProperties.getTokenTTL());
            // 6.封装VO返回
            UserLoginVO vo = new UserLoginVO();
            vo.setUserId(userDB.getId());
            vo.setUsername(userDB.getUsername());
            vo.setToken(token);
            return vo;
        }else {
            throw new BadRequestException("邮箱或密码错误");
        }
    }

    @Override
    public R<?> editPassword(LoginFormByEmailDTO loginFormByEmailDTO) {
        // 1.数据校验
        String email = loginFormByEmailDTO.getEmail();
        String password = loginFormByEmailDTO.getPassword();
        // 2.根据邮箱查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        User userDB = userMapper.selectOne(queryWrapper);
        if (userDB!=null&&userDB.getPassword().equals(password)){
            if (userDB.getPassword().equals(loginFormByEmailDTO.getNewPassword())){
                return R.error("新密码不能与旧密码一致");
            }
            userDB.setPassword(loginFormByEmailDTO.getNewPassword());
            userMapper.updateById(userDB);
            return R.ok("修改成功");
        }else {
            throw new BadRequestException("邮箱或密码错误");
        }
    }

//    @Override
//    public R register(RegisterFormDTO registerFormDTO) {
//        // 1.数据校验
//        String username = registerFormDTO.getUsername();
//        String password = registerFormDTO.getPassword();
//        String phone = registerFormDTO.getPhone();
//        // 2.根据用户名或手机号查询
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("username", username);
//        User userDB = userMapper.selectOne(queryWrapper);
//        if (userDB==null){
//            if (userDB.getPhone().equals(phone)){
//                throw new BadRequestException("手机号重复");
//            }
//            User user = new User();
//            BeanUtils.copyProperties(registerFormDTO,user);
//            userMapper.insert(user);
//            return R.ok("注册成功");
//        }
//        return R.ok("用户已被注册");
//
//    }


}
